#ifndef SIMPLE_SHARED_PTR_HH
#define SIMPLE_SHARED_PTR_HH


struct ControlBlock{
    int ref_count;
    ControlBlock() : ref_count(1) {}
};

template<typename T>
class SimpleSharedPtr{
public:
    SimpleSharedPtr() : ptr(nullptr), control_block(nullptr) {}
    explicit SimpleSharedPtr(T *p);
    ~SimpleSharedPtr();
    SimpleSharedPtr(const SimpleSharedPtr &rhs);
    SimpleSharedPtr& operator=(const SimpleSharedPtr &rhs);
    SimpleSharedPtr(SimpleSharedPtr &&rhs) noexcept;
    T* operator->() const;
    T& operator*() const;
    T* get() const;
    int use_count() const;
    void reset(T* p);
private:
    T* ptr;
    ControlBlock* control_block;
    void release();
};

// 带参数的构造函数实现
template<typename T>
SimpleSharedPtr<T>::SimpleSharedPtr(T *p) : ptr(p) {
    if(p)
        control_block = new ControlBlock();
    else
        control_block = nullptr;
}

// 析构函数实现
template<typename T> 
SimpleSharedPtr<T>::~SimpleSharedPtr() {
    release();
}

// 拷贝构造函数实现
template<typename T> 
SimpleSharedPtr<T>::SimpleSharedPtr(const SimpleSharedPtr<T> &rhs) : ptr(rhs.ptr), control_block(rhs.control_block) {
    if(control_block)
        ++control_block->ref_count;
}

// 赋值运算符重载实现
template<typename T>
SimpleSharedPtr<T>& SimpleSharedPtr<T>::operator=(const SimpleSharedPtr<T> &rhs) {
    if(this != &rhs) {
        release();
        ptr = rhs.ptr;
        control_block = rhs.control_block;
        if(control_block)
            ++control_block->ref_count;
    }
    return *this;
}

// 释放资源函数实现
template<typename T>
void SimpleSharedPtr<T>::release() {
    if(control_block) {
        --control_block->ref_count;
        if(control_block->ref_count == 0) {
            delete ptr;
            ptr = nullptr;
            delete control_block;
            control_block = nullptr;
        }
    }
}

// reset 函数实现
template<typename T>
void SimpleSharedPtr<T>::reset(T *p) {
    release();
    ptr = p;
    if(p)
        control_block = new ControlBlock();
    else
        control_block = nullptr;
}

// 移动构造函数实现
template<typename T>
SimpleSharedPtr<T>::SimpleSharedPtr(SimpleSharedPtr<T> &&rhs) noexcept : ptr(rhs.ptr), control_block(rhs.control_block) {
    rhs.ptr = nullptr;
    rhs.control_block = nullptr;
}

// 箭头运算符重载实现
template<typename T>
T* SimpleSharedPtr<T>::operator->() const {
    return ptr;
}

// 解引用运算符重载实现
template<typename T>
T& SimpleSharedPtr<T>::operator*() const {
    return *ptr;
}

// get 函数实现
template<typename T>
T* SimpleSharedPtr<T>::get() const {
    return ptr;
}

// use_count 函数实现
template<typename T>
int SimpleSharedPtr<T>::use_count() const {
    return control_block ? control_block->ref_count : 0;
}

#endif